package top.jacktgq.lock.reentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import top.jacktgq.utils.LogUtils;

/**
 * 
 * @Title: TestReentrantLock.java 
 * @Package top.jacktgq.lock 
 * @Description: 多线程之固定运行：使用await和signal
 * @author CandyWall   
 * @date 2020年11月1日 下午5:49:07 
 * @version V1.0
 */
public class Demo5_2_await_signal {
	private static ReentrantLock lock = new ReentrantLock();
	private static Condition waitSet = lock.newCondition();
	private static boolean t2runned = false;	//表示t2是否运行过
	public static void main(String[] args) {
		Thread t1 = new Thread(() -> {
				lock.lock();
				try {
					while(!t2runned) {
						LogUtils.log("Demo5_2_await_signal", "t2没有运行，进入等待...");
						try {
							waitSet.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					LogUtils.log("Demo5_2_await_signal", "线程执行了...");
				} finally {
					lock.unlock();
				}
		}, "t1");
		Thread t2 = new Thread(() -> {
			lock.lock();
			try {
				LogUtils.log("Demo5_2_await_signal", "线程执行了...");
				t2runned = true;
				waitSet.signalAll();	//唤醒t1线程
			} finally {
				lock.unlock();
			}
		}, "t2");
		t1.start();
		t2.start();
	}	
}
